import cv2
import os
from driver.orbbec_img import *


# ========== 配置项 ==========
SAVE_DIR    = "captures"      # 保存照片的目录
WINDOW_NAME = "Camera"        # OpenCV 窗口名称

os.makedirs(SAVE_DIR, exist_ok=True)

def get_next_filename():
    """生成下一个保存文件名，格式 img_0001.jpg"""
    existing = sorted(f for f in os.listdir(SAVE_DIR)
                      if f.startswith("img_") and f.endswith(".jpg"))
    idx = 1 if not existing else int(existing[-1][4:-4]) + 1
    return f"img_{idx:04d}.jpg"

def main():
    cap = OrbbecCamera(color=True, depth=False)
    cap.start()
    saved_files = []   # 已保存图片的完整路径列表
    view_idx    = -1   # -1 表示实时摄像头模式

    cv2.namedWindow(WINDOW_NAME, cv2.WINDOW_NORMAL)

    while True:
        # —— 根据模式获取要显示的帧 —— 
        if view_idx == -1:
            # 实时摄像头
            frame ,_ = cap.read_frames()

            display = frame.copy()
        else:
            # 浏览已保存图片
            path = saved_files[view_idx]
            display = cv2.imread(path)
            if display is None:
                # 读图失败则退回实时模式
                print("无法读取图片，退回实时模式：", path)
                view_idx = -1
                continue

        # —— 在画面左上角叠加操作提示 —— 
        overlay = display.copy()
        hints = [
            "[Space] 拍照并保存 / 返回实时",
            "[a] ← 上一张",
            "[s] 下一张",
            "[d] 删除当前图",
            "[Esc] 退出"
        ]
        for i, txt in enumerate(hints):
            cv2.putText(overlay, txt, (10, 30 + i*30),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255,255,255), 2, cv2.LINE_AA)
        cv2.addWeighted(overlay, 0.4, display, 0.6, 0, display)

        cv2.imshow(WINDOW_NAME, display)
        key = cv2.waitKey(1) & 0xFF

        if key == 27:  # ESC
            break

        elif key == ord(' '):
            if view_idx == -1:
                # 实时模式下拍照
                filename = get_next_filename()
                fullpath = os.path.join(SAVE_DIR, filename)
                cv2.imwrite(fullpath, frame)
                saved_files.append(fullpath)
                print("已保存:", fullpath)
            else:
                # 浏览模式下返回实时
                view_idx = -1

        elif key == ord('a'):
            # 上一张
            if saved_files:
                if view_idx == -1:
                    view_idx = len(saved_files) - 1
                else:
                    view_idx = max(0, view_idx - 1)

        elif key == ord('s'):
            # 下一张
            if saved_files:
                if view_idx == -1:
                    view_idx = 0
                else:
                    view_idx = min(len(saved_files) - 1, view_idx + 1)

        elif key == ord('d'):
            # 删除当前浏览的图片
            if view_idx >= 0:
                to_del = saved_files.pop(view_idx)
                try:
                    os.remove(to_del)
                    print("已删除:", to_del)
                except Exception as e:
                    print("删除失败:", e)
                # 调整索引：如果删到了末尾，就回退一张；删完就回实时
                if view_idx >= len(saved_files):
                    view_idx = len(saved_files) - 1
                if not saved_files:
                    view_idx = -1

    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()
